//
//  ViewController.m
//  WJCoreDataAccess-example
//
//  Created by Yunhai.Wu on 15/12/16.
//  Copyright © 2015年 WJ. All rights reserved.
//

#import "ViewController.h"
#import <CoreData/CoreData.h>
#import "QWCoreDataDA.h"
#import "QWLoggingMacros.h"
#import "UserMO.h"

@interface ViewController ()<UITableViewDelegate,UITableViewDataSource,NSFetchedResultsControllerDelegate>
@property (nonatomic, weak) UITableView *tableView;
@property (nonatomic, strong) NSFetchedResultsController *fetchedResultsController;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [[QWCoreDataManager sharedObject] setDatabaseName:@"WJCoreDataAccess_example"];
    [[QWCoreDataManager sharedObject] setModelName:@"WJCoreDataAccess_example"];
    
    if (!_tableView) {
        UITableView *t = [[UITableView alloc] initWithFrame:self.view.bounds];
        [t setAutoresizingMask:UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleHeight];
        [t setDelegate:self];
        [t setDataSource:self];
        [self.view addSubview:t];
        _tableView = t;
    }
    self.navigationItem.title = @"CoreDataAccess";
    
    UIBarButtonItem *leftBarItem = [[UIBarButtonItem alloc] initWithTitle:@"Remove" style:UIBarButtonItemStylePlain target:self action:@selector(leftExec:)];
    self.navigationItem.leftBarButtonItem = leftBarItem;
    
    UIBarButtonItem *rightBarItem = [[UIBarButtonItem alloc] initWithTitle:@"Add" style:UIBarButtonItemStylePlain target:self action:@selector(rightExec:)];
    self.navigationItem.rightBarButtonItem = rightBarItem;
    
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] initWithEntityName:@"UserMO"];
    [fetchRequest setSortDescriptors:@[[NSSortDescriptor sortDescriptorWithKey:@"uid" ascending:YES]]];
    self.fetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:[NSManagedObjectContext defaultContext] sectionNameKeyPath:nil cacheName:nil];
    [self.fetchedResultsController setDelegate:self];
    
    NSError *error = nil;
    if (![self.fetchedResultsController performFetch:&error]) {
        QWLogError(@"performFetch error:%@",error);
        abort();
    }
}

-(void) leftExec:(id) sender {
    
    UserMO *user = [[self.fetchedResultsController fetchedObjects] lastObject];
    if (user) {
        [user delete];
        [user save];
    }
}

-(void) rightExec:(id) sender {
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSManagedObjectContext *context = [NSManagedObjectContext defaultContext];
        UserMO *user = [UserMO createInContext:context];
        NSTimeInterval t = [[NSDate date] timeIntervalSince1970];
        [user setNick:[NSString stringWithFormat:@"%0.0f",t]];
        [user setAge:33];
        [user setUid:(long)t];
        
        [user save];
    });
    
}

#pragma mark NSFetchedResultsControllerDelegate
- (void)controllerDidChangeContent:(NSFetchedResultsController *)controller {
    [self.tableView reloadData];
}

#pragma mark UITableViewDelegate
-(CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 44.0f;
}

#pragma mark UITableViewDataSource
-(NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [[_fetchedResultsController fetchedObjects] count];
}
-(UITableViewCell*) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *kCellId = @"kCellId";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kCellId];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:kCellId];
//        [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
    }
    [self configureCell:cell atIndexPath:indexPath];
    return cell;
}

-(void) configureCell:(UITableViewCell*) cell atIndexPath:(NSIndexPath *)indexPath {
    UserMO *user = [_fetchedResultsController objectAtIndexPath:indexPath];
    cell.textLabel.text = [user nick];
    cell.detailTextLabel.text = [NSString stringWithFormat:@"%li  %li",(long)[user uid],(long)[user age]];
}

@end
